package com.cool.reggie.core;

import com.cool.reggie.utils.BaseContext;
import com.cool.reggie.utils.ResultData;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author ifredomvip@gmail.com
 * @Date 2022/7/4 11:18
 * @Version 1.0.0
 * @Description
 **/
@Slf4j
@WebFilter(filterName = "LoginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    public final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
//        log.info("拦截到请求 {}", request.getRequestURL());


        String requestUri = request.getRequestURI();

        String[] whiteUrls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/common/**",
                "/front/**",
                "/backend/**",
                "/user/sendMsg",
                "/user/login"
        };

        Boolean check = checkWhiteUrl(whiteUrls, requestUri);

        if (check) {
            filterChain.doFilter(request, response);
            return;
        }
        System.out.println("非白名单，拦截");

        // 判断登录状态，如果已登录，则放行
        if (request.getSession().getAttribute("employee") != null) {

            Long employeeId = (Long)request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(employeeId);
            filterChain.doFilter(request, response);
            return;
        }

        // 移动端判断登录状态，如果已登录，则放行
        if (request.getSession().getAttribute("user") != null) {
            Long userId = (Long)request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request, response);
            return;
        }

        ObjectMapper objectMapper = new ObjectMapper();

        response.getWriter().write(objectMapper.writeValueAsString(ResultData.error("NOTLOGIN")));

    }

    Boolean checkWhiteUrl(String[] urls, String requestUri) {
        for (String url : urls) {
            if (antPathMatcher.match(url, requestUri)) {
                return true;
            }
        }
        return false;
    }
}
